package com.pmt.feedplayer.android

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.pmt.feedplayer.ui.VideoListViewModel
import java.io.File
import android.os.Environment
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.List
import androidx.compose.ui.Alignment
import com.pmt.feedplayer.data.VideoItem
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

/**
 * 视频标签页内容
 */
@Composable
fun VideoTabContent(viewModel: VideoListViewModel, paddingValues: PaddingValues) {
    Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
        // 显示视频列表
        com.pmt.feedplayer.ui.VideoFeed(
            videos = viewModel.videoListState.value,
            onVideoClick = { video: VideoItem -> viewModel.onVideoClick(video) },
            onLoadMore = { viewModel.loadMoreVideos(10) }
        )
        
        // 当showPlayer为true时，显示视频播放页面
        if (viewModel.showPlayer.value && viewModel.selectedVideo.value != null) {
            viewModel.selectedVideo.value?.let { video ->
                com.pmt.feedplayer.ui.VideoPlayerScreen(
                    videoItem = video,
                    onBack = { viewModel.closePlayer() }
                )
            }
        }
    }
}

/**
 * 音频文件数据类
 */
data class AudioItem(
    val id: String,
    val title: String,
    val filePath: String,
    val duration: Long,
    val size: Long
)

/**
 * 音频标签页内容
 */
@Composable
fun AudioTabContent(paddingValues: PaddingValues) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    var audioList by remember { mutableStateOf<List<AudioItem>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    
    // 加载音频文件
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            try {
                val musicDir = context.getExternalFilesDir(Environment.DIRECTORY_MUSIC)
                if (musicDir != null && musicDir.exists()) {
                    val audioFiles = musicDir.listFiles { _, name ->
                        name.endsWith(".aac", ignoreCase = true) || 
                        name.endsWith(".mp3", ignoreCase = true) ||
                        name.endsWith(".wav", ignoreCase = true)
                    } ?: emptyArray()
                    
                    audioList = audioFiles.mapIndexed { index, file ->
                        AudioItem(
                            id = "${file.name}_${index}",
                            title = file.nameWithoutExtension,
                            filePath = file.absolutePath,
                            duration = 0, // 简化实现，实际应该解析音频文件获取时长
                            size = file.length()
                        )
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                isLoading = false
            }
        }
    }
    
    Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
        if (isLoading) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        } else if (audioList.isEmpty()) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Text("暂无音频文件")
                    Text("从视频中提取音频后会显示在这里", modifier = Modifier.padding(top = 8.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
        } else {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(audioList) { audio ->
                    AudioItemCard(audio)
                }
                item {
                    Spacer(modifier = Modifier.height(16.dp))
                }
            }
        }
    }
}

/**
 * 音频项列表组件
 */
@Composable
fun AudioItemCard(audio: AudioItem) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp, vertical = 6.dp)
            .clickable {
                // 这里可以添加音频播放逻辑
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 小型音频图标
        Box(
            modifier = Modifier
                .size(48.dp)
                .background(MaterialTheme.colorScheme.primaryContainer)
                .align(Alignment.CenterVertically)
        ) {
            Icon(
                imageVector = Icons.Filled.List,
                contentDescription = "音频图标",
                modifier = Modifier
                    .size(24.dp)
                    .align(Alignment.Center),
                tint = MaterialTheme.colorScheme.primary
            )
        }
        
        // 音频信息
        Column(modifier = Modifier
            .weight(1f)
            .padding(horizontal = 12.dp)
        ) {
            Text(
                text = audio.title,
                fontWeight = MaterialTheme.typography.bodyMedium.fontWeight,
                fontSize = MaterialTheme.typography.bodyMedium.fontSize,
                maxLines = 1,
                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
            )
            
            Text(
                text = formatFileSize(audio.size),
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                style = MaterialTheme.typography.bodySmall,
                fontSize = MaterialTheme.typography.bodySmall.fontSize
            )
        }
    }
}

/**
 * 设置标签页内容
 */
@Composable
fun SettingsTabContent(paddingValues: PaddingValues) {
    var isDarkMode by remember { mutableStateOf(false) }
    var enableAudioExtraction by remember { mutableStateOf(true) }
    var enableTranslation by remember { mutableStateOf(false) }
    
    Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
        LazyColumn(modifier = Modifier.fillMaxSize()) {
            item {
                SectionHeader("外观")
                SwitchSettingItem(
                    title = "深色模式",
                    description = "使用深色主题",
                    checked = isDarkMode,
                    onCheckedChange = { isDarkMode = it }
                )
            }
            
            item {
                SectionHeader("功能")
                SwitchSettingItem(
                    title = "启用音频提取",
                    description = "允许从视频中提取音频",
                    checked = enableAudioExtraction,
                    onCheckedChange = { enableAudioExtraction = it }
                )
                SwitchSettingItem(
                    title = "启用翻译功能",
                    description = "允许在视频播放时进行语音翻译",
                    checked = enableTranslation,
                    onCheckedChange = { enableTranslation = it }
                )
            }
            
            item {
                SectionHeader("关于")
                SettingItem(
                    title = "版本",
                    value = "1.0.0",
                    onClick = {}
                )
                SettingItem(
                    title = "开发者",
                    value = "FeedPlayer Team",
                    onClick = {}
                )
            }
            
            item {
                Spacer(modifier = Modifier.height(32.dp))
            }
        }
    }
}

/**
 * 设置项部分标题
 */
@Composable
fun SectionHeader(title: String) {
    Text(
        text = title,
        style = MaterialTheme.typography.labelMedium,
        color = MaterialTheme.colorScheme.primary,
        modifier = Modifier.padding(16.dp, 16.dp, 16.dp, 8.dp)
    )
}

/**
 * 开关设置项
 */
@Composable
fun SwitchSettingItem(title: String, description: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .background(MaterialTheme.colorScheme.surface),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(text = title, fontWeight = MaterialTheme.typography.bodyLarge.fontWeight)
            Text(text = description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = MaterialTheme.colorScheme.primary
            )
        )
    }
}

/**
 * 普通设置项
 */
@Composable
fun SettingItem(title: String, value: String, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .background(MaterialTheme.colorScheme.surface)
            .clickable(onClick = onClick),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = title, fontWeight = MaterialTheme.typography.bodyLarge.fontWeight, modifier = Modifier.weight(1f))
        Text(text = value, color = MaterialTheme.colorScheme.onSurfaceVariant)
    }
}

/**
 * 格式化文件大小
 */
fun formatFileSize(bytes: Long): String {
    if (bytes < 0) return "未知"
    if (bytes < 1024) return "${bytes}B"
    if (bytes < 1024 * 1024) return "${String.format("%.1f", bytes / 1024.0)}KB"
    return "${String.format("%.1f", bytes / (1024.0 * 1024.0))}MB"
}